package com.sky.utils;


import com.alibaba.fastjson.JSONObject;
import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.dysmsapi20170525.models.SendSmsResponseBody;
import com.aliyun.teautil.models.RuntimeOptions;
import com.sky.result.Result;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class SmsUtil {
    private static final String ACCESS_KEY_ID = "LTAI5tGfKuYuGu6jxfikD2gf";

    private static final String ACCESS_KEY_SECRET = "Xr8hdgDpuIbpBLzSYExJDNOVtGTp2A";

    private static final String SIGN_NAME  =  "普仁医连网";

    private static  final String TEMPLATE_CODE="SMS_266930623";
    public static Client createClient() throws Exception {
        // 工程代码建议使用更安全的无AK方式，凭据配置方式请参见：https://help.aliyun.com/document_detail/378657.html。
        com.aliyun.credentials.Client credential = new com.aliyun.credentials.Client();
        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
                .setCredential(credential)
                .setAccessKeyId(ACCESS_KEY_ID)
                .setAccessKeySecret(ACCESS_KEY_SECRET)
                .setRegionId("cn-hangzhou")
                // Client 超时参数设置
                // 连接超时默认 5 * 1000 毫秒
                .setConnectTimeout(5000)
                // 读超时默认 10 * 1000 毫秒
                .setReadTimeout(10000);
        // Endpoint 请参考 https://api.aliyun.com/product/Dysmsapi
        config.endpoint = "dysmsapi.aliyuncs.com";
        return new Client(config);
    }
    public static Result<String> sendSms(String phoneNum, String code) throws Exception {
        // 创建请求对象并设置入参
        SendSmsRequest sendSmsRequest = new SendSmsRequest()
                .setSignName(SIGN_NAME)
                .setTemplateCode(TEMPLATE_CODE)
                .setPhoneNumbers(phoneNum)
                .setTemplateParam("{\"code\": \"" + code + "\"}");
        //创建运行时参数
        RuntimeOptions runtime = new RuntimeOptions();
        Client client = createClient();
       //发起请求
        SendSmsResponse response = null;
        try {
            response = client.sendSmsWithOptions(sendSmsRequest, runtime);
        } catch (Exception e) {
            log.info("发送阿里云短信报错信息：{}", e.getMessage());
            e.printStackTrace();
        }
        if(response == null) {
            throw new AssertionError("sendSmsResponse is null!");
        }
        SendSmsResponseBody body = response.getBody();

        if(body.getCode()==null||!body.getCode().equals("OK")) {
            log.info("短信发送失败");
            return Result.error("短信发送失败");
        }else {
            log.info("短信发送成功");
            return Result.success(code);
        }
    };
}
